#include "../board/sdk_project_config.h"
#include <stdio.h>
#include <stdlib.h>
#include "pwm_driver.h"
#include <string.h>
//*********串口定时器参数配置************//
#define BUFFER_SIZE 21U
#define INST_UART_SAMPLE  INST_UART_1
#define INST_UART4_SAMPLE INST_UART_4
#define INST_PCTMR_0 (0U)
#define INST_PCTMR_1 (1U)
#define INST_PCTMR_2 (2U)
//***********数据发送和读取指令**********//
uint8_t C02_cmd[]={0x03,0x03,0x00,0x00,0x00,0x04,0x45,0xeb};
uint8_t Tht_cmd[]={0x02,0x03,0x00,0x00,0x00,0x04,0x44,0x3a};
uint8_t co2_transmet[]={0xEE,0xB1,0x10,0x00,0x02,0x00,0x05,0x00,0x00,0x00,0x00,0xFF,0xFC,0xFF,0xFF};//从下标7开始
uint8_t thl_transmet[]={0xEE,0xB1,0x12,0x00,0x02,0x00,0x02,0x00,0x04,0x00,0x00,0x2E,0x00,0x00,0x03,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x04,0x00,0x00,0x2E,0x00,0xFF,0xFC,0xFF,0xFF};
uint8_t button_open[]={0xee,0xb1,0x10,0x00,0x03,0x00,0x04,0x00,0xff,0xfc,0xff,0xff};//按钮弹起
uint8_t button_close[]={0xee,0xb1,0x10,0x00,0x03,0x00,0x04,0x01,0xff,0xfc,0xff,0xff};//按钮按下
uint8_t text_close[]={0xEE,0xB1,0x10,0x00,0x03,0x00,0x07,0xB9,0xD8,0xFF,0xFC,0xFF,0xFF};//关
uint8_t text_open[]={0xEE,0xB1,0x10,0x00,0x03,0x00,0x07,0xBF,0xAA,0xFF,0xFC,0xFF,0xFF};//开
uint8_t g_buffer[BUFFER_SIZE];
uint8_t g_bufferIdx;
uint8_t re1_flag=1U;
uint8_t re2_flag=1U;
//串口四中断接收参数****//
#define CTBUFFER_SIZE 15U
uint8_t ct_buffer[CTBUFFER_SIZE];
uint8_t ct_bufferIdx;
//pwm相关参数配置**********//
#define INST_PWM_0 (0U)
#define INST_PWM_1 (1U)
#define INST_PWM_3 (3U)
pwm_state_t g_stPwmState_1;
pwm_state_t g_stPwmState_2;
pwm_state_t g_stPwmState_3;
uint8_t pwm_arry[3]={0};
//******屏幕上传数据**************//
uint16_t tempeture=0;
uint16_t light=0;
unsigned char co2_output[4] = {0,0,0,0};
unsigned char humit_output[4] = {0,0,0,0};
unsigned char temp_output[4] = {0,0,0,0};
unsigned char lux_output[4] = {0,0,0,0};
uint16_t tim_outpt[2]={0};
//*********定时器计数************//
uint16_t g_timerCount0 = 0U;//数据发送计数
uint16_t g_timerCount1 = 0U;//数据发送计数
uint16_t g_timerCount2 = 0U;//系统指示计数
uint16_t g_timerCount3 = 0U;//定时计数
uint8_t time_flag=0;
uint8_t close_flag=0;
//*********************//
pctmr_config_t g_stPctmr0Config0 = {//PCTMR时钟频率是10MHZ
    .dmaRequest      = false,
    .interruptEnable = true,
    .freeRun         = false,
    .workMode        = PCTMR_WORKMODE_TIMER,
    .clockSelect     = PCTMR_CLOCKSOURCE_ERCLK,
    .prescaler       = PCTMR_PRESCALE_2,
    .bypassPrescaler = false,
    .compareValue    = 1999,
    .counterUnits    = PCTMR_COUNTER_UNITS_TICKS,
    .pinSelect       = PCTMR_PINSELECT_TRGMUX,
    .pinPolarity     = PCTMR_PINPOLARITY_RISING,
    .callBack        = NULL,
    .parameter       = NULL,
};//200us
pctmr_config_t g_stPctmr0Config1 = {//PCTMR时钟频率是10MHZ
    .dmaRequest      = false,
    .interruptEnable = true,
    .freeRun         = false,
    .workMode        = PCTMR_WORKMODE_TIMER,
    .clockSelect     = PCTMR_CLOCKSOURCE_ERCLK,
    .prescaler       = PCTMR_PRESCALE_16_GLITCHFILTER_8,
    .bypassPrescaler = false,
    .compareValue    = 12549,
    .counterUnits    = PCTMR_COUNTER_UNITS_TICKS,
    .pinSelect       = PCTMR_PINSELECT_TRGMUX,
    .pinPolarity     = PCTMR_PINPOLARITY_RISING,
    .callBack        = NULL,
    .parameter       = NULL,
};//10ms
pctmr_config_t g_stPctmr0Config2 = {//PCTMR时钟频率是10MHZ
    .dmaRequest      = false,
    .interruptEnable = true,
    .freeRun         = false,
    .workMode        = PCTMR_WORKMODE_TIMER,
    .clockSelect     = PCTMR_CLOCKSOURCE_ERCLK,
    .prescaler       = PCTMR_PRESCALE_8192_GLITCHFILTER_4096,
    .bypassPrescaler = false,
    .compareValue    = 2440,
    .counterUnits    = PCTMR_COUNTER_UNITS_TICKS,
    .pinSelect       = PCTMR_PINSELECT_TRGMUX,
    .pinPolarity     = PCTMR_PINPOLARITY_RISING,
    .callBack        = NULL,
    .parameter       = NULL,
};//10ms
//PWM初始化,freq=40M
pwm_config_t g_stPwm1Config0 = {
    .period          = 100,
    .duty            = 0,
    .pwm_clk_src_cfg = G_CLK,
    .pwm_polarity    = S_RV_C_CMP,
    .pwm_active_cfg  = 0x1,
    .prescaler       = 0x190,
    .repeat          = ONCE,
    .water_mark      = 4,
    .int_type        = 0x7,
    .callback        = NULL,
    .callbackParam   = NULL,
};
pwm_config_t g_stPwm1Config1 = {
    .period          = 100,
    .duty            = 0,
    .pwm_clk_src_cfg = G_CLK,
    .pwm_polarity    = S_RV_C_CMP,
    .pwm_active_cfg  = 0x1,
    .prescaler       = 0x190,
    .repeat          = ONCE,
    .water_mark      = 4,
    .int_type        = 0x7,
    .callback        = NULL,
    .callbackParam   = NULL,
};
pwm_config_t g_stPwm1Config3 = {
    .period          = 100,
    .duty            = 0,
    .pwm_clk_src_cfg = G_CLK,
    .pwm_polarity    = S_RV_C_CMP,
    .pwm_active_cfg  = 0x1,
    .prescaler       = 0x190,
    .repeat          = ONCE,
    .water_mark      = 4,
    .int_type        = 0x7,
    .callback        = NULL,
    .callbackParam   = NULL,
};
int hexBytesToAsciiHex(unsigned char byte1, unsigned char byte2, unsigned char out[]) {//十六进制转ASCII码
    unsigned short combined = (byte1 << 8) | byte2;
    char str[10];
    snprintf(str, sizeof(str), "%d", combined);
    for (int i = 0; str[i] != '\0'; i++) {
        out[i] = str[i];
    }
    return strlen(str);
}
int hexBytesToInt(unsigned char byte1, unsigned char byte2) {//16进制转十进制
    if (byte1 >= 0x30 && byte1 <= 0x39 && byte2 >= 0x30 && byte2 <= 0x39) {
        int num1 = byte1 - 0x30;
        int num2 = byte2 - 0x30;
        return num1 * 10 + num2;
    }
    return -1;
}
void PCTMR_ISR(void *data)//PCTIM中断函数
{
    (void)data;
    g_timerCount0++;
    g_timerCount1++;
    if(g_timerCount0==9000){
    	g_timerCount0=0;
		PINS_DRV_WritePin(PORTC,3,1);//发送数据使能
		re1_flag=UART_DRV_SendData(INST_UART_SAMPLE,C02_cmd,8);//读二氧化碳
    }
    if(g_timerCount1==9600){
    	g_timerCount1=0;
		PINS_DRV_WritePin(PORTC,3,1);//发送数据使能
		re2_flag=UART_DRV_SendData(INST_UART_SAMPLE,Tht_cmd,8);//读二氧化碳
    }
    PCTMR_DRV_ClearIntFlag(INST_PCTMR_0);
}
void PCTMR1_ISR(void *data)//PCTIM中断函数
{
    (void)data;
    g_timerCount2++;
    if(g_timerCount2==50){
    	PINS_DRV_TogglePin(PORTD,14);
    	g_timerCount2=0;
   }
    PCTMR_DRV_ClearIntFlag(INST_PCTMR_1);
}
void PCTMR2_ISR(void *data)//PCTIM中断函数
{
    (void)data;
    if(time_flag){
    	g_timerCount3++;
		if(g_timerCount3==tim_outpt[0]*60){
			g_timerCount3=0;
			time_flag=0;
			close_flag=1;
			g_stPwm1Config0.duty=0;
			PWM_DRV_Cfg(INST_PWM_0,&g_stPwmState_1,&g_stPwm1Config0);//PWM参数配置函数
			g_stPwm1Config1.duty=0;
			PWM_DRV_Cfg(INST_PWM_1,&g_stPwmState_2,&g_stPwm1Config1);//PWM参数配置函数
			g_stPwm1Config3.duty=0;
			PWM_DRV_Cfg(INST_PWM_3,&g_stPwmState_3,&g_stPwm1Config3);//PWM参数配置函数
			PINS_DRV_TogglePin(PORTC,28);
		}
    }
    if(close_flag){
    	g_timerCount3++;
		if(g_timerCount3==tim_outpt[1]*60){
			g_timerCount3=0;
			close_flag=0;
			time_flag=1;
			g_stPwm1Config0.duty=pwm_arry[0];;
			PWM_DRV_Cfg(INST_PWM_0,&g_stPwmState_1,&g_stPwm1Config0);//PWM参数配置函数
			g_stPwm1Config1.duty=pwm_arry[1];;
			PWM_DRV_Cfg(INST_PWM_1,&g_stPwmState_2,&g_stPwm1Config1);//PWM参数配置函数
			g_stPwm1Config3.duty=pwm_arry[2];;
			PWM_DRV_Cfg(INST_PWM_3,&g_stPwmState_3,&g_stPwm1Config3);//PWM参数配置函数
			PINS_DRV_TogglePin(PORTC,28);
		}
    }
    PCTMR_DRV_ClearIntFlag(INST_PCTMR_2);
}
void PCTMR_INit(void)//PCTIM初始化
{
    lin_pctmr_config_t linPctmrConf = {0};
    linPctmrConf.pctmrInstance      = INST_PCTMR_0;
    g_stPctmr0Config0.callBack  = PCTMR_ISR;
    g_stPctmr0Config0.parameter = (void *)&linPctmrConf;
    PCTMR_DRV_Init(INST_PCTMR_0, &g_stPctmr0Config0);
    PCTMR_DRV_StartCounter(INST_PCTMR_0);
}
void PCTMR1_INit(void)//PCTIM初始化
{
    lin_pctmr_config_t linPctmrConf1 = {0};
    linPctmrConf1.pctmrInstance      = INST_PCTMR_1;
    g_stPctmr0Config1.callBack  = PCTMR1_ISR;
    g_stPctmr0Config1.parameter = (void *)&linPctmrConf1;
    PCTMR_DRV_Init(INST_PCTMR_1, &g_stPctmr0Config1);
    PCTMR_DRV_StartCounter(INST_PCTMR_1);
}
void PCTMR2_INit(void)//PCTIM初始化
{
    lin_pctmr_config_t linPctmrConf2 = {0};
    linPctmrConf2.pctmrInstance      = INST_PCTMR_2;
    g_stPctmr0Config2.callBack  = PCTMR2_ISR;
    g_stPctmr0Config2.parameter = (void *)&linPctmrConf2;
    PCTMR_DRV_Init(INST_PCTMR_2, &g_stPctmr0Config2);
    PCTMR_DRV_StartCounter(INST_PCTMR_2);
}
void RxCallback(void *driverState, uart_event_t event, void *userData)//串口中断回调函数
{
    (void)driverState;
    (void)userData;
    if (event == UART_EVENT_RX_FULL) {
        if (g_bufferIdx >= BUFFER_SIZE - 1) {//g_bufferIdx为数组下标，buff为10，所以最大为9
        	if(g_buffer[8]==0x03){
        		hexBytesToAsciiHex(g_buffer[11],g_buffer[12],co2_output);
        		co2_transmet[7]=co2_output[0];co2_transmet[8]=co2_output[1];
        		co2_transmet[9]=co2_output[2];co2_transmet[10]=co2_output[3];
        		UART_DRV_SendData(INST_UART4_SAMPLE,co2_transmet,15);
        	}
        	if(g_buffer[8]==0x02){
        		tempeture=g_buffer[13]<<8|g_buffer[14];
        		light=g_buffer[17]<<8|g_buffer[18];
        		hexBytesToAsciiHex(g_buffer[11],g_buffer[12],humit_output);
        		hexBytesToAsciiHex(g_buffer[13],g_buffer[14],temp_output);
        		hexBytesToAsciiHex(g_buffer[17],g_buffer[18],lux_output);
        		thl_transmet[9]=temp_output[0];thl_transmet[10]=temp_output[1];
        		thl_transmet[12]=temp_output[2];
        		thl_transmet[25]=humit_output[0];thl_transmet[26]=humit_output[1];
        		thl_transmet[28]=humit_output[2];
        		thl_transmet[17]=lux_output[0];thl_transmet[18]=lux_output[1];
        		thl_transmet[19]=lux_output[2];thl_transmet[20]=lux_output[3];
        		UART_DRV_SendData(INST_UART4_SAMPLE,thl_transmet,33);
        	}
            g_bufferIdx = 0;
        }
        else {
            g_bufferIdx++;
            UART_DRV_ReceiveData(INST_UART_SAMPLE,g_buffer,1U);
        }
        UART_DRV_SetRxBuffer(INST_UART_SAMPLE, &g_buffer[g_bufferIdx], 1U);
    }
}
//串口四接收回调函数
void Rx4_Callback(void *driverState, uart_event_t event, void *userData)//串口中断回调函数
{
    (void)driverState;
    (void)userData;
    if (event == UART_EVENT_RX_FULL) {
        if (ct_bufferIdx >= CTBUFFER_SIZE - 1) {
        	if(ct_buffer[6]==0x04){
        		pwm_arry[0]=hexBytesToInt(ct_buffer[8],ct_buffer[9]);
        	}else if(ct_buffer[6]==0x05){
        		pwm_arry[1]=hexBytesToInt(ct_buffer[8],ct_buffer[9]);
        	}else if(ct_buffer[6]==0x06){
        		pwm_arry[2]=hexBytesToInt(ct_buffer[8],ct_buffer[9]);
        	}
        	if(ct_buffer[4]==0x05&&ct_buffer[6]==0x03){
        		tim_outpt[0]=hexBytesToInt(ct_buffer[8],ct_buffer[9]);
        	}else if(ct_buffer[4]==0x05&&ct_buffer[6]==0x04){
        		tim_outpt[1]=hexBytesToInt(ct_buffer[8],ct_buffer[9]);
        	}
        	if(ct_buffer[1]==0x01){
        		if(ct_buffer[2]==0x01){
        			PINS_DRV_WritePin(PORTD,17,1);
        		}
        		else{
        			PINS_DRV_WritePin(PORTD,17,0);
        		}
        	}else if(ct_buffer[1]==0x02){
        		if(ct_buffer[2]==0x01){
        			PINS_DRV_WritePin(PORTD,9,1);
        		}
        		else{
        			PINS_DRV_WritePin(PORTD,9,0);
        		}
        	}else if(ct_buffer[1]==0x03){
        		if(ct_buffer[2]==0x01){
        			PINS_DRV_WritePin(PORTC,4,1);
        		}
        		else{
        			PINS_DRV_WritePin(PORTC,4,0);
        		}
        	}else if(ct_buffer[1]==0x04){
        		if(ct_buffer[2]==0x01){
        		    g_stPwm1Config0.duty=pwm_arry[0];
        		    PWM_DRV_Cfg(INST_PWM_0,&g_stPwmState_1,&g_stPwm1Config0);//PWM参数配置函数
        		}
        	}else if(ct_buffer[1]==0x05){
        		if(ct_buffer[2]==0x01){
        		    g_stPwm1Config1.duty=pwm_arry[1];
        		    PWM_DRV_Cfg(INST_PWM_1,&g_stPwmState_2,&g_stPwm1Config1);//PWM参数配置函数
        		}
        	}else if(ct_buffer[1]==0x06){
        		if(ct_buffer[2]==0x01){
        		    g_stPwm1Config3.duty=pwm_arry[2];
        		    PWM_DRV_Cfg(INST_PWM_3,&g_stPwmState_3,&g_stPwm1Config3);//PWM参数配置函数
        		}
        	}else if(ct_buffer[1]==0x07){
        		if(ct_buffer[2]==0x01){
        			time_flag=1;
        		}
        		else{
        			close_flag=0;
        			time_flag=0;
        			g_timerCount3=0;
        		}
        	}
            ct_bufferIdx = 0;
        }
        else {
            ct_bufferIdx++;
            UART_DRV_ReceiveData(INST_UART4_SAMPLE,ct_buffer,1U);
        }
        UART_DRV_SetRxBuffer(INST_UART4_SAMPLE, &ct_buffer[ct_bufferIdx], 1U);
    }
}
void SYS_Init(void)//系统初始化
{
	CLOCK_SYS_Init(g_pstClockManConfigsArr[0]);//初始化时钟
    PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_stPinmuxConfigArr);
    UART_DRV_Init(INST_UART_SAMPLE, &g_stUartState_1, &g_stUart1UserConfig0);
    UART_DRV_Init(INST_UART4_SAMPLE, &g_stUartState_4, &g_stUart4UserConfig0);
    UART_DRV_InstallRxCallback(INST_UART4_SAMPLE, Rx4_Callback, NULL);
    UART_DRV_ReceiveData(INST_UART4_SAMPLE,ct_buffer,1U);
    UART_DRV_InstallRxCallback(INST_UART_SAMPLE, RxCallback, NULL);
    UART_DRV_ReceiveData(INST_UART_SAMPLE,g_buffer,1U);
    PINS_DRV_WritePin(PORTC,3,0);//接收数据使能
}
void Ctral_Init(void){
	PINS_DRV_WritePin(PORTD,9,0);//继电器二关闭
	PINS_DRV_WritePin(PORTD,17,0);//继电器一关闭
	PINS_DRV_WritePin(PORTC,4,0);//继电器三关闭
}
void PWMCtral_Init(void){
    PWM_DRV_Init(INST_PWM_0, &g_stPwmState_1, &g_stPwm1Config0);
    PWM_DRV_Init(INST_PWM_1, &g_stPwmState_2, &g_stPwm1Config1);
    PWM_DRV_Init(INST_PWM_3, &g_stPwmState_3, &g_stPwm1Config3);
    PWM_DRV_Start(INST_PWM_0);
    PWM_DRV_Start(INST_PWM_1);
    PWM_DRV_Start(INST_PWM_3);
}
int main(void)
{
	uint8_t ctral_flag=0;
	uint8_t oldctral_flag=0;
	SYS_Init();//系统初始化(包括引脚初始化，串口初始化，时钟初始化)
	PCTMR_INit();//定时器初始化
	PCTMR1_INit();
	PCTMR2_INit();
	Ctral_Init();//继电器控制引脚初始化
	PWMCtral_Init();//使能PWM
	while(1){
		if(re1_flag==STATUS_SUCCESS||re2_flag==STATUS_SUCCESS){
			OS_DelayMs(10);
			PINS_DRV_WritePin(PORTC,3,0);//接收数据使能
			re1_flag=1U;
			re2_flag=1U;
		}
		if(light>0x01f4){//光照大于定值，蜂鸣器报警
			PINS_DRV_WritePin(PORTB,11,1);
		}else{
			PINS_DRV_WritePin(PORTB,11,0);
		}
		if(tempeture>0x0109){
			ctral_flag=1;
			if(ctral_flag!=oldctral_flag){
				PINS_DRV_WritePin(PORTC,4,1);//继电器打开，按钮关闭
				OS_DelayMs(100);
				UART_DRV_SendData(INST_UART4_SAMPLE,button_close,12);
				OS_DelayMs(100);
				UART_DRV_SendData(INST_UART4_SAMPLE,text_open,13);
			}
			oldctral_flag=ctral_flag;
		}else{
			ctral_flag=2;
			if(ctral_flag!=oldctral_flag){
				PINS_DRV_WritePin(PORTC,4,0);//继电器关闭，按钮弹起
				OS_DelayMs(100);
				UART_DRV_SendData(INST_UART4_SAMPLE,button_open,12);
				OS_DelayMs(100);
				UART_DRV_SendData(INST_UART4_SAMPLE,text_close,13);
			}
			oldctral_flag=ctral_flag;
		}
	}
}
